package com.easyjop.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;

import com.easyjop.entity.enums.PostStatusEnum;
import com.easyjop.entity.enums.ResponseCodeEnum;
import com.easyjop.entity.po.Category;
import com.easyjop.entity.po.ExamQuestionItem;
import com.easyjop.entity.query.CategoryQuery;
import com.easyjop.entity.query.ExamQuestionItemQuery;
import com.easyjop.exception.BusinessException;
import com.easyjop.mappers.ACommonMapper;
import com.easyjop.mappers.ExamQuestionItemMapper;
import com.easyjop.service.CategoryService;
import com.easyjop.service.ExamQuestionItemService;
import org.springframework.stereotype.Service;

import com.easyjop.entity.enums.PageSize;
import com.easyjop.entity.query.ExamQuestionQuery;
import com.easyjop.entity.po.ExamQuestion;
import com.easyjop.entity.vo.PaginationResultVO;
import com.easyjop.entity.query.SimplePage;
import com.easyjop.mappers.ExamQuestionMapper;
import com.easyjop.service.ExamQuestionService;
import com.easyjop.utils.StringTools;
import org.springframework.transaction.annotation.Transactional;


/**
 * 考试题目 业务接口实现
 */
@Service("examQuestionService")
public class ExamQuestionServiceImpl implements ExamQuestionService {

	@Resource
	private ExamQuestionMapper<ExamQuestion, ExamQuestionQuery> examQuestionMapper;
	@Resource
	private CategoryService categoryService;
	@Resource
	private ExamQuestionItemMapper<ExamQuestionItem, ExamQuestionItemQuery> examQuestionItemMapper;
	@Resource
	private ACommonMapper aCommonMapper;


	/**
	 * 根据条件查询列表
	 */
	@Override
	public List<ExamQuestion> findListByParam(ExamQuestionQuery param) {
		return this.examQuestionMapper.selectList(param);
	}

	/**
	 * 根据条件查询列表
	 */
	@Override
	public Integer findCountByParam(ExamQuestionQuery param) {
		return this.examQuestionMapper.selectCount(param);
	}

	/**
	 * 分页查询方法
	 */
	@Override
	public PaginationResultVO<ExamQuestion> findListByPage(ExamQuestionQuery param) {
		int count = this.findCountByParam(param);
		int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

		SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
		param.setSimplePage(page);
		List<ExamQuestion> list = this.findListByParam(param);
		PaginationResultVO<ExamQuestion> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
		return result;
	}

	/**
	 * 新增
	 */
	@Override
	public Integer add(ExamQuestion bean) {
		return this.examQuestionMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	@Override
	public Integer addBatch(List<ExamQuestion> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.examQuestionMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	@Override
	public Integer addOrUpdateBatch(List<ExamQuestion> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.examQuestionMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 多条件更新
	 */
	@Override
	public Integer updateByParam(ExamQuestion bean, ExamQuestionQuery param) {
		StringTools.checkParam(param);
		return this.examQuestionMapper.updateByParam(bean, param);
	}

	/**
	 * 多条件删除
	 */
	@Override
	public Integer deleteByParam(ExamQuestionQuery param) {
		StringTools.checkParam(param);
		return this.examQuestionMapper.deleteByParam(param);
	}

	/**
	 * 根据QuestionId获取对象
	 */
	@Override
	public ExamQuestion getExamQuestionByQuestionId(Integer questionId) {
		return this.examQuestionMapper.selectByQuestionId(questionId);
	}

	/**
	 * 根据QuestionId修改
	 */
	@Override
	public Integer updateExamQuestionByQuestionId(ExamQuestion bean, Integer questionId) {
		return this.examQuestionMapper.updateByQuestionId(bean, questionId);
	}

	/**
	 * 根据QuestionId删除
	 */
	@Override
	public Integer deleteExamQuestionByQuestionId(Integer questionId) {
		return this.examQuestionMapper.deleteByQuestionId(questionId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveExamQuestion(ExamQuestion examQuestion, List<ExamQuestionItem> examQuestionItemList, Boolean superAdmin) {
		Integer questionId = examQuestion.getQuestionId();
		if (questionId==null){
			/*新增*/
			examQuestion.setCreateTime(new Date());
			this.examQuestionMapper.insert(examQuestion);
		}
		else {
			/*修改*/
			examQuestion.setQuestionType(null);

			ExamQuestion dbInfo = this.examQuestionMapper.selectByQuestionId(examQuestion.getQuestionId());
			//只能自己发布的才能修改
			if (!dbInfo.getCreateUserId().equals(examQuestion.getCreateUserId()) && !superAdmin) {
				throw new BusinessException(ResponseCodeEnum.CODE_600);
			}
			examQuestion.setCreateUserId(null);
			examQuestion.setCreateUserName(null);
			examQuestion.setCreateTime(null);
			this.examQuestionMapper.updateByQuestionId(examQuestion, questionId);
		}
		examQuestionItemList.forEach(itm->{
			itm.setQuestionId(examQuestion.getQuestionId());
		});
		/*更新的选项*/
		List<ExamQuestionItem> updataItemList = examQuestionItemList.stream().filter(itm ->
			itm.getItemId() != null
		).collect(Collectors.toList());
		/*新增的选项*/
		List<ExamQuestionItem> addItemList = examQuestionItemList.stream().filter(itm ->
				itm.getItemId() == null
		).collect(Collectors.toList());
		Map<Integer, ExamQuestionItem> paramItemMap = updataItemList.stream().collect(Collectors.toMap(ExamQuestionItem::getItemId,
				Function.identity(),
				(file1, file2) -> file2));
		ExamQuestionItemQuery itemQuery=new ExamQuestionItemQuery();
		itemQuery.setQuestionId(questionId);
		List<ExamQuestionItem> dbItemList = examQuestionItemMapper.selectList(itemQuery);
		List<Integer> delList = new ArrayList<>();
		if (!paramItemMap.isEmpty()) {
			//数据库中有，传入的参数中没有，就是已删除
			for (ExamQuestionItem db : dbItemList) {
				if (paramItemMap.get(db.getItemId()) == null) {
					delList.add(db.getItemId());
				}
			}
		}
		//新增
		if (!addItemList.isEmpty()) {
			examQuestionItemMapper.insertBatch(addItemList);
		}

		//修改
		for (ExamQuestionItem item : updataItemList) {
			examQuestionItemMapper.updateByItemId(item, item.getItemId());
		}

		//删除的
		if (!delList.isEmpty()) {
			examQuestionItemMapper.deleteBatch(delList);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)

	public void delExamQuestionBatch(String s, Integer userId) {
		String[] split = s.split(",");
		if (userId!=null){
			ExamQuestionQuery infoQuery = new ExamQuestionQuery();
			infoQuery.setQuestionIds(split);
			List<ExamQuestion> examQuestions = examQuestionMapper.selectList(infoQuery);
			Stream<ExamQuestion> examQuestionStream = examQuestions.stream().filter(itm -> !itm.getCreateUserId().equals(userId));
			if (examQuestionStream!=null || examQuestions.size()>0){
				throw new BusinessException(ResponseCodeEnum.CODE_606);
			}
		}
		examQuestionItemMapper.deleteBatchByQuestionId(split, PostStatusEnum.NO_POST.getStatus(), userId);
		ExamQuestionQuery examQuestionQuery = new ExamQuestionQuery();
		examQuestionQuery.setQuestionIds(split);
		examQuestionQuery.setStatus(PostStatusEnum.NO_POST.getStatus());
		examQuestionMapper.deleteByParam(examQuestionQuery);
	}

	@Override
	public ExamQuestion showDetailNext(ExamQuestionQuery query, Integer nextType, Integer currentId) {
		if (nextType == null) {
			query.setQuestionId(currentId);
		} else {
			query.setNextType(nextType);
			query.setCurrentId(currentId);
		}
		ExamQuestion examQuestion = examQuestionMapper.showDetailNext(query);
		if (examQuestion == null && nextType == null) {
			throw new BusinessException("内容不存在");
		}
		if (examQuestion == null && nextType == -1) {
			throw new BusinessException("已经是第一条了");
		} else if (examQuestion == null && nextType == 1) {
			throw new BusinessException("已经是最后一条了");
		}
		ExamQuestionItemQuery itemQuery = new ExamQuestionItemQuery();
		itemQuery.setQuestionId(examQuestion.getQuestionId());
		itemQuery.setOrderBy("sort asc");
		List<ExamQuestionItem> questionItemList = examQuestionItemMapper.selectList(itemQuery);
		examQuestion.setQuestionItemList(questionItemList);
		return examQuestion;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public ExamQuestion getExamQuestionAndItmByQuestionId(Integer questionId) {
		ExamQuestion examQuestion = this.examQuestionMapper.selectByQuestionId(questionId);
		if (examQuestion==null||!PostStatusEnum.POST.getStatus().equals(examQuestion.getStatus())){
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		ExamQuestionItemQuery examQuestionItemQuery = new ExamQuestionItemQuery();
		examQuestionItemQuery.setQuestionId(questionId);
		examQuestionItemQuery.setOrderBy("sort asc");
		List<ExamQuestionItem> examQuestionItems = examQuestionItemMapper.selectList(examQuestionItemQuery);
		examQuestion.setQuestionItemList(examQuestionItems);
		return examQuestion;
	}
}